#include "a9main.h"

#define N 8

int cgiMain() 
{ 
	key_t key;
	char buf[N];
	int msgid;
	CGI_cmd msg_buf;
    M0_cmd m0;
	memset(&msg_buf,0,sizeof(msg_buf));
	
	cgiFormString("fan",buf,N);

	if((key = ftok("/app", 'g')) < 0)
	{
		perror("ftok");
		exit(1);
	}
#if 0
	if((msgid = msgget(key, 0666)) < 0)
	{
		perror("msgget");
		exit(1);
	}
#endif
	msgid = msgget(key,IPC_CREAT|IPC_EXCL|0666);
    if(msgid == -1)
	{
	    if(errno == EEXIST)
		{
		    msgid = msgget(key,0666);
		}else{
		    perror("fail to msgget");
			exit(1);
		}
	}

	bzero (msg_buf.text, sizeof (msg_buf.text));

	switch (buf[0])
	{
		case '0':
			{

				m0.dev = FAN;
				m0.command=OFF;

				memcpy(&msg_buf.text[0],&m0,sizeof(m0));
				break;
			}
		case '1':
			{
				m0.dev = FAN;
				m0.command=FAN_ON_1;

				memcpy(&msg_buf.text[0],&m0,sizeof(m0));
				break;
			}
		case '2':
			{
				m0.dev = FAN;
				m0.command=FAN_ON_2;

				memcpy(&msg_buf.text[0],&m0,sizeof(m0));
				break;
			}
		case '3':
			{
				m0.dev = FAN;
				m0.command=FAN_ON_3;

				memcpy(&msg_buf.text[0],&m0,sizeof(m0));
				break;
			}
	}
    msg_buf.mytype = 1;	
	msg_buf.type = M0_ctl;
	msgsnd(msgid, &msg_buf,sizeof(msg_buf)-sizeof(long),0);



	cgiHeaderContentType("text/html\n\n"); 
	fprintf(cgiOut, "<HTML><HEAD>\n"); 
	fprintf(cgiOut, "<TITLE>My CGI</TITLE></HEAD>\n"); 
	fprintf(cgiOut, "<BODY>"); 

	fprintf(cgiOut, "<H2>send sucess</H2>");

	//fprintf(cgiOut, "<a href='.html'>返回</a>"); 
	fprintf(cgiOut, "<meta http-equiv=\"refresh\" content=\"1;url=../m0_1.html\">");
	fprintf(cgiOut, "</BODY>\n"); 
	fprintf(cgiOut, "</HTML>\n"); 


	return 0; 
} 
